import db from "../../db.js";
const save = async (data) => {
  const [result] = await db.query(
    "INSERT INTO `article`(`name`,`model_id`) values?",
    [data]
  );
  if (result?.affectedRows > 0) {
    return {
      affectedRows: result?.affectedRows,
      id: result?.insertId,
    };
  }
  return false;
};
const getList = async () => {
  const [rows] = await db.query(
    "SELECT id,name from article WHERE isDelete=0 "
  );
  return rows || [];
};
const getDetails = async (id) => {
  const [rows] = await db.query(
    "SELECT content.value,fields.label,fields.id as fieldId,fields.name as fieldName,article.name as name,model.name as modelName,model.id as modelId,fields.label,fields.type from `content` left join fields on content.field_id=fields.id left join model on content.model_id=model.id left join article on article.id=content.article_id  WHERE content.isDelete=0 and article.isDelete=0 and content.article_id=?",
    id
  );
  return rows || null;
};
const update = async (id, fields) => {
  const [result] = await db.query("update `article` set?  where id=?", [
    fields,
    id,
  ]);
  if (result?.affectedRows > 0) {
    return true;
  }
  return false;
};
const del = async (id) => {
  const [result] = await db.query(
    "update   `article` set isDelete=1 where id=?",
    id
  );
  if (result?.affectedRows > 0) {
    return true;
  }
  return false;
};
const findById = async (id) => {
  const [rows] = await db.query(
    "select id,name from `article` where isDelete=0 and id=? limit 1",
    id
  );
  return rows || [];
};
export default {
  save,
  getList,
  getDetails,
  update,
  del,
  findById,
};
